public class RemoveNthFromEnd {
    // 删除链表的倒数第n个节点
    // https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        if (head == null) {
            return head;
        }
        ListNode fast = head;
        for (int i = 0; i < n; i++) {
            fast = fast.next;
            if (i != n-1 && fast == null) {
                return head;
            }
        }
        ListNode slow = head;
        ListNode prev = null;
        while (fast != null) {
            prev = slow;
            slow = slow.next;
            fast = fast.next;
        }
        if (slow == head) {
            head = head.next;
        } else {
            prev.next = slow.next;
        }
        return head;
    }
}
